/**
 * 
 */
package io.gitee.falllee.dao.generator;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.util.StringUtility;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import io.gitee.falllee.dao.annotation.Table;

/**
 * @author batty
 *
 */
public class DaoCommentGenerator implements CommentGenerator {

    private static final String SYNC_DATE_PRECISION = "syncDatePrecision";
    private static final String SYNC_DATE_PRECISION_ENUM_MICROSECOND = "SyncDatePrecisionEnum.MICROSECOND";
    private static final String SYNC_DATE_PRECISION_ENUM_MILLISECOND = "SyncDatePrecisionEnum.MILLISECOND";
    private static final String SYNC_DATE_PRECISION_ENUM_SENCEND = "SyncDatePrecisionEnum.SENCEND";
    private static final String SIX = "6";
    private static final String THREE = "3";
    private static final String VALUE = "value";
    private Properties properties;
    private Properties systemPro;
    private boolean suppressDate;
    private boolean suppressAllComments;
    private String currentDateStr;

    public DaoCommentGenerator() {
        super();
        properties = new Properties();
        systemPro = System.getProperties();
        suppressDate = false;
        suppressAllComments = false;
        currentDateStr = (new SimpleDateFormat("yyyy/MM/dd")).format(new Date());
    }

    @Override
    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = StringUtility.isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));

        suppressAllComments =
            StringUtility.isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
        IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        String remark = introspectedColumn.getRemarks();
        sb.append(!StringUtils.hasLength(remark) ? introspectedColumn.getActualColumnName() : remark);
        field.addJavaDocLine(sb.toString());

        // addJavadocTag(field, false);

        field.addJavaDocLine(" */");
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine(" */");
    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        // 添加serialVersionUID
        addField(topLevelClass);
        addImportClass(topLevelClass);
        addTableContent(topLevelClass, introspectedTable);
        // 添加类注释
        addClassComment(topLevelClass, introspectedTable);
    }

    private void addImportClass(TopLevelClass topLevelClass) {
        topLevelClass.addImportedType(new FullyQualifiedJavaType("io.gitee.falllee.dao.annotation.Column"));
        topLevelClass.addImportedType(new FullyQualifiedJavaType("io.gitee.falllee.dao.annotation.Table"));
    }

    private void addField(TopLevelClass topLevelClass) {
        Field field = new Field("serialVersionUID", new FullyQualifiedJavaType("long"));
        field.addJavaDocLine("");
        field.setFinal(true);
        field.setInitializationString("1L");
        field.setStatic(true);
        field.setVisibility(JavaVisibility.PRIVATE);
        topLevelClass.addField(field);
    }

    private void addClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        StringBuilder sb = new StringBuilder();
        topLevelClass.addJavaDocLine("/**");
        sb.append(" * ");
        String remark = introspectedTable.getRemarks();
        remark = !StringUtils.hasLength(remark) ? introspectedTable.getFullyQualifiedTable().getIntrospectedTableName()
            : remark;
        sb.append(remark);
        topLevelClass.addJavaDocLine(sb.toString());
        topLevelClass.addJavaDocLine(" * ");
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(systemPro.getProperty("user.name"));
        topLevelClass.addJavaDocLine(sb.toString());
        sb.setLength(0);
        sb.append(" * @date ");
        sb.append(currentDateStr);
        topLevelClass.addJavaDocLine(sb.toString());
        topLevelClass.addJavaDocLine(" */");
    }

    private void addTableContent(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        StringBuilder sbTable = new StringBuilder();
        java.lang.reflect.Method[] methods = Table.class.getMethods();
        for (int i = 0; i < methods.length; i++) {
            java.lang.reflect.Method method = methods[i];
            String methodName = method.getName();
            if (methodName.equals(VALUE)) {
                continue;
            }
            String val = getTablePropery(introspectedTable, methodName);
            if (!StringUtils.hasLength(val)) {
                continue;
            }
            if (method.getReturnType().equals(String.class)) {
                sbTable.append(String.format(", %s = \"%s\"", methodName, val));
            } else {
                if (SYNC_DATE_PRECISION.equals(methodName)) {
                    val = getSyncDatePrecision(val);
                }
                sbTable.append(String.format(", %s = %s", methodName, val));
            }
        }
        // 添加@Table注解
        if (sbTable.length() > 0) {
            if (sbTable.toString().contains(SYNC_DATE_PRECISION)) {
                topLevelClass
                    .addImportedType(new FullyQualifiedJavaType("io.gitee.falllee.dao.annotation.SyncDatePrecisionEnum"));
            }
            sbTable.insert(0, String.format("@Table(value = \"%s\"", introspectedTable.getFullyQualifiedTable()));
            sbTable.append(")");
            topLevelClass.addAnnotation(sbTable.toString());
        } else {
            topLevelClass.addAnnotation(String.format("@Table(\"%s\")", introspectedTable.getFullyQualifiedTable()));
        }
    }

    private String getSyncDatePrecision(String val) {
        String res = SYNC_DATE_PRECISION_ENUM_SENCEND;
        switch (val) {
            case THREE:
                res = SYNC_DATE_PRECISION_ENUM_MILLISECOND;
                break;
            case SIX:
                res = SYNC_DATE_PRECISION_ENUM_MICROSECOND;
                break;
            default:
                break;
        }
        return res;
    }

    private String getTablePropery(IntrospectedTable introspectedTable, String propertyName) {
        TableConfiguration obj = introspectedTable.getTableConfiguration();
        return obj.getProperty(propertyName);
    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {}

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerEnum.addJavaDocLine("/**");
        // addJavadocTag(innerEnum, false);
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString());
        innerEnum.addJavaDocLine(" */");
    }

    @Override
    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
        IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        method.addJavaDocLine("/**");

        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        String remark = introspectedColumn.getRemarks();
        sb.append(!StringUtils.hasLength(remark) ? introspectedColumn.getActualColumnName() : remark);
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" * ");

        sb.setLength(0);
        sb.append(" * @return ");
        sb.append(introspectedColumn.getActualColumnName());
        method.addJavaDocLine(sb.toString());

        method.addJavaDocLine(" */");

        int order = introspectedTable.getAllColumns().indexOf(introspectedColumn) + 1;
        // 添加@Column注解
        List<IntrospectedColumn> pkList = introspectedTable.getPrimaryKeyColumns();
        // 如果存在多个主键，仅标记第一个为主键列
        if (!CollectionUtils.isEmpty(pkList) && pkList.get(0).equals(introspectedColumn)) {
            method.addAnnotation(String.format("@Column(value = \"%s\", key = true, order = %d)",
                introspectedColumn.getActualColumnName(), order));
        } else {
            method.addAnnotation(
                String.format("@Column(value = \"%s\", order = %d)", introspectedColumn.getActualColumnName(), order));
        }
    }

    @Override
    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
        IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

        method.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        String remark = introspectedColumn.getRemarks();
        sb.append(!StringUtils.hasLength(remark) ? introspectedColumn.getActualColumnName() : remark);
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" * ");

        Parameter parm = method.getParameters().get(0);
        sb.setLength(0);
        sb.append(" * @param ");
        sb.append(parm.getName());
        method.addJavaDocLine(sb.toString());
        method.addJavaDocLine(" */");
    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addComment(XmlElement xmlElement) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addRootComment(XmlElement rootElement) {
        // TODO Auto-generated method stub

    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do not wish to include the Javadoc tag -
     * however, if you do not include the Javadoc tag then the Java merge capability of the eclipse plugin will break.
     *
     * @param javaElement
     *            the java element
     */
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag and XML comments. You may return null if
     * you do not want the date in these documentation elements.
     *
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        String result = null;
        if (!suppressDate) {
            result = currentDateStr;
        }
        return result;
    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
        Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable,
        IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
        Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable,
        IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable,
        Set<FullyQualifiedJavaType> imports) {
        // TODO Auto-generated method stub
        
    }
}
